package com.ks.controller;

import com.ks.base.BaseAction;
import com.ks.entity.*;
import com.ks.service.*;
import com.ks.util.HtmlUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <br>
 * <b>功能：</b>practiceMngController<br>
 * <b>作者：</b>www.jeecg.org<br>
 * <b>日期：</b> Feb 2, 2013 <br>
 * <b>版权所有：<b>版权所有(C) 2013，www.jeecg.org<br>
 */
@Controller
@RequestMapping("/practice")
public class practiceMngController extends BaseAction {

    private final static Logger log = Logger.getLogger(practiceMngController.class);

    // Servrice start
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private DepositoryService<Depository> depositoryService;
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private QuestionService<Question> questionService;
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private PracticeService<Practice> practiceService;
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private ContentService<Content> contentService;
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private ContentQuestionService<ContentQuestion> contentQuestionService;
    @Autowired(required = false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
    private PaperStudentQuestionService<PaperStudentQuestion> paperStudentQuestionService;
    @Autowired(required = false)
    private PaperStudentService<PaperStudent> paperStudentService;
    @Autowired(required = false)
    private StudentQuestionService<StudentQuestion> studentQuestionService;
    /**
     * @param paperid 传过来的是题型id  1 2 3
     * @return
     * @throws Exception
     */
    @RequestMapping("/onlinetesting")
    public ModelAndView list(Integer paperid,HttpSession session) throws Exception {
        User user = (User) session.getAttribute("userInfo");
        Map<String, Object> context = questionService.onlinetesting(user.getId(),paperid);
        if(paperid==1){
            return forword("/pages/practice/practice-single", context);
        }
        if(paperid==2){
            return forword("/pages/practice/practice-muti", context);
        }
        if(paperid==3){
            return forword("/pages/practice/practice-judge", context);
        }
        return forword("/pages/practice/item-knows", context);
    }


    /**
     * @param response
     * @throws Exception
     */
    @RequestMapping("/contentList")
    public void contentList(HttpServletRequest request,HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("userInfo");
        //设置页面数据
        Map<String, Object> map = new HashMap<>();
        String depositoryid = request.getParameter("depositoryid");
        if (StringUtils.isBlank(depositoryid)) {
            List<Depository> list = depositoryService.queryList(null);
            if (list.size()>0) {
                Depository entity = list.get(0);
                depositoryid = entity.getId().toString();
            }
        }
        int countQuestion = 0;
        map.put("desp_id",depositoryid);
        List<Content> list = contentService.queryList(map);
        Map<String,Object> context = new HashMap<>();
        context.put("userId",user.getId());
        for (Content content : list) {
            content.setCount(contentQuestionService.findCountByContentId(content.getId()));
            context.put("id",content.getId());
            content.setDoneCount(studentQuestionService.findCountJoinContent(context));
        }
        map.put("countContent",countQuestion);
        map.put("countQuestion",list.size());
        HtmlUtil.writerJson(response, list);
    }

    /**
     *
     *  添加 countPractice 已经练过的试题数量 correctCount 正确答案数量
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryCount")
    @ResponseBody
    public Map<String, Object> queryCount(HttpServletRequest request,HttpServletResponse response) throws Exception {
        User user = (User) request.getSession().getAttribute("userInfo");
        Map<String, Object> resultMap = new HashMap<>();
        //设置页面数据
        Map<String, Object> map = new HashMap<>();
        String depositoryid = request.getParameter("depositoryid");
        map.put("desp_id",depositoryid);
        List<Content> list = contentService.queryList(map);
        map.put("userId",user.getId());
        int countQuestion = 0;
        int countPractice = 0;
        int correctCount = 0;
        for (Content content : list) {
            map.put("id",content.getId());
            countQuestion += contentQuestionService.findCountByContentId(content.getId());
            countPractice += studentQuestionService.findCountJoinContent(map);
            correctCount += studentQuestionService.findCountJoinContentCorrect(map);
        }
        Depository depository = depositoryService.queryById(depositoryid);
        resultMap.put("countPractice",countPractice);
        resultMap.put("correctCount",correctCount);
        resultMap.put("countContent",list.size());
        resultMap.put("countQuestion",countQuestion);
        resultMap.put("depositoryImg",depository.getPicture());
        return resultMap;
    }

    @RequestMapping("/delete")
    public void delete(String[] id, HttpServletResponse response) throws Exception {
        depositoryService.delete(id);
        sendSuccessMessage(response, "删除成功");
    }

    @RequestMapping("practicetest")
    public ModelAndView practicetest(){
        Map<String, Object> context = getRootMap();
        Map<String, Object> map = new HashMap<>();
        map.put("questiontype_id",1);
        context.put("singlelist", questionService.findAll(map));
        map.put("questiontype_id",2);
        context.put("mutilist", questionService.findAll(map));
        map.put("questiontype_id",3);
        context.put("judgelist", questionService.findAll(map));
        System.out.println(map);
        return forword("/pages/practice/exam-exercise", context);
    }

    /**
     * @param id 题库下的知识点id
     * @return
     */
    @RequestMapping("practicexercise")
    public ModelAndView practicexercise(String id){
        Map<String,Object> context = questionService.practicexercise(id);
        return forword("/pages/practice/practice-exercise", context);
    }

    @RequestMapping("/judgeAjax")
    @ResponseBody
    public Question judgeAjax(String id){
        return questionService.findAnswerById(id);
    }

    @RequestMapping("/mockList")
    public void mockList(PaperStudent entity,HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("userInfo");
        //设置页面数据
        Map<String, Object> jsonMap = new HashMap<>();
        entity.setUser_id(user.getId());
        List<PaperStudent> list = paperStudentService.queryList(entity);
        for (PaperStudent paperStudent : list) {
            Date date = paperStudent.getCreatetime();
            DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            paperStudent.setCreatetimeStr(format1.format(date));
        }

        HtmlUtil.writerJson(response, list);
    }

    /**
     * 考生新增模拟考试    生成试卷
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("createAnalogPaper")
    public void createAnalogPaper(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("userInfo");
        String contentids = request.getParameter("contentids");
        //设置页面数据
        String[] ids = contentids.split(",");
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap = practiceService.createAnalogPaper(user,ids);
        HtmlUtil.writerJson(response, jsonMap);

    }
    @RequestMapping("gotoPractice")
    public ModelAndView gotoPractice(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession(false);
        String paperid = request.getParameter("paperid");
        //设置页面数据
        Map<String,Object> map = practiceService.queryPaperByPaperId(paperid);
        return forword("/pages/practice/onlinetesting", map);
    }
    /**
     * 考生交卷算分
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/calculation")
    public ModelAndView calculation(String paperid, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("userInfo");
        Map<String, Object> context = practiceService.calculation(paperid);
        context.put("user",user);
        return forword("/pages/practice/practice-results", context);
    }
    /**
     * 添加或修改试题答案
     *
     * @param entity   ExamPaperStudentAnswer
     * @param response
     * @throws Exception
     */
    @RequestMapping("/answersAdd")
    @ResponseBody
    public void answersAdd(PaperStudentQuestion entity, HttpServletResponse response) {

        paperStudentQuestionService.updateAnswersByPaperIdAndQuestionId(entity);
        sendSuccessMessage(response, "保存成功~");
    }

    @RequestMapping("wrongAjax")
    @ResponseBody
    public void wrongAjax(HttpSession session,StudentQuestion studentQuestion)throws Exception {
        User user = (User)session.getAttribute("userInfo");
        studentQuestion.setUser_id(user.getId());
        studentQuestionService.wrongAjax(studentQuestion);
    }
    /**
     * 考生的答题面板
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping("/answerDetail")
    public void answerDetail(HttpServletRequest request, HttpServletResponse response) {

        String paper_id = request.getParameter("paper_id");
        //设置页面数据
        Map<String, Object> jsonMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("paper_user_id",paper_id);
        //单选
        map.put("questiontype_id",1);
        List<PaperStudentQuestion> singlelist = paperStudentQuestionService.queryPaperUserQuestions(map);
        //多选
        map.put("questiontype_id",2);
        List<PaperStudentQuestion> mutilist = paperStudentQuestionService.queryPaperUserQuestions(map);
        //判断
        map.put("questiontype_id",3);
        List<PaperStudentQuestion> judgelist = paperStudentQuestionService.queryPaperUserQuestions(map);
        jsonMap.put("singleans", singlelist);
        jsonMap.put("mutians", mutilist);
        jsonMap.put("judgeans", judgelist);
        HtmlUtil.writerJson(response, jsonMap);
    }

    /**
     *模拟考试学生答题情况
     */
    @RequestMapping("/paperDetails")
    public ModelAndView paperDetails(String paperid, HttpServletRequest request) throws Exception{
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("userInfo");
        PaperStudent entity = paperStudentService.queryById(paperid);
        String studentid = request.getParameter("studentid");
        String studentName = request.getParameter("studentName");
        String score = request.getParameter("score");
        Map<String, Object> context = practiceService.queryUserPaperResults(paperid,entity);
        context.put("studentName", user.getName());
        context.put("paper", entity);
        return forword("/pages/practice/userPractice", context);
    }

    /**
     * 考生页面 错题练习 之前 判断是否有错题 ajax 返回 map集合
     * @param paperId 试题类型id
     * @return
     */
    @RequestMapping("/onlinetestingAjax")
    @ResponseBody
    public Map<String,Object> onlinetestingAjax(Integer paperId,HttpSession session){
        User user = (User) session.getAttribute("userInfo");
        Map<String,Object> map = questionService.onlinetestingAjax(user.getId(),paperId);
        return map;
    }
    /**
     * 考生页面 错题练习 之前 判断是否有错题 ajax 返回 map集合
     * @param paperid 试题类型id
     * @return
     */
    @RequestMapping("/paperWarnning")
    @ResponseBody
    public Map<String,Object> paperWarnning(String paperid,HttpSession session){
        User user = (User) session.getAttribute("userInfo");
        Map<String, Object> context = practiceService.paperWarnning(paperid);

        return context;
    }
}
